/*
 *
 *	@author David Alvarez Lopez
 *	@email  sly.dekar@gmail.com
 *	@date	29-Oct-05
 *
 */
 
package com.dekaru.data;

public class LinkedList {

	private Node head;

	public LinkedList() {
	
		head = null;	
	}
	
	public Node getHead() {
	
		return head;	
	}
	
	public void setHead(Node head) {
	
		this.head = head;	
	}

	public void addFirst(Object data) {
		
		Node n = new Node(data, getHead());
		
		setHead(n);
	}
	
	public void addLast(Object data) {
		
		Node n = new Node(data);
		
		if(getHead() == null) {
		
			setHead(n);	
		}
		else {
		
			Node current = getHead();
			
			while(current.getNext() != null) {
			
				current = current.getNext();	
			}
			
			current.setNext(n);	
		}
	}
	
	public int size() {
		
		int counter = 0;
		
		Node current = getHead();
		
		while(current != null) {
		
			current = current.getNext();
			counter++;	
		}
		
		return counter;
	}
	
	public Object get(int index) throws NullPointerException {
		
		Node current = getHead();
		
		for(int i = 0; i < index; i++) {
		
			current = current.getNext();	
		}
		
		return current.getData();
	}
	
	public int indexOf(Object data) {
		
		int counter = 0;
		
		Node current = getHead();
		
		while(current != null) {
		
			if(current.getData().toString().equals(data.toString())) {
			
				return counter;	
			}
			else {
			
				current = current.getNext();
				counter++;	
			}
		}
		
		return -1;
	}
	
	public Object remove(int index) throws NullPointerException {

		Object temp;

		if (index == 0) {
		
			temp = getHead().getData();
			setHead(getHead().getNext());
		} 
		else {
	
			Node current = getHead();
			
			for (int i = 0; i < index - 1; ++i)  {
	
				current = current.getNext();
			}
	
			temp = current.getNext().getData();
			current.setNext(current.getNext().getNext());
		}
	
		return temp;
	}

	
	public String toString() {
		
		Node current = getHead();
		
		String st = "";
		
		while(current != null) {
		
			st += current.getData().toString();
			current = current.getNext();	
		}
	
		return st;
	}
	
	public boolean isEmpty() {
		
		return (head == null);
	}
}